<template>
	<div class="wrapper">
	  <!-- header部分 -->
	  <header>
		<i class="fa fa-angle-left" @click="goBack"></i>
		<p>编辑送货地址</p>
	  </header>

	  <!-- 表单部分 -->
	  <div class="form-container">
	    <div class="form-card">
	      <div class="form-group">
	        <label for="contactName">
	          <i class="fa fa-user"></i>
	          <span>联系人</span>
	        </label>
	        <input
	          type="text"
	          id="contactName"
	          v-model="deliveryAddress.contactName"
	          placeholder="请输入联系人姓名"
	        />
	      </div>
	      
	      <div class="form-group gender-group">
	        <label>
	          <i class="fa fa-venus-mars"></i>
	          <span>性别</span>
	        </label>
	        <div class="radio-group">
	          <label class="radio-label" :class="{'active': deliveryAddress.contactSex == '1'}">
	            <input
	              type="radio"
	              v-model="deliveryAddress.contactSex"
	              value="1"
	            />
	            <span>先生</span>
	          </label>
	          <label class="radio-label" :class="{'active': deliveryAddress.contactSex == '0'}">
	            <input
	              type="radio"
	              v-model="deliveryAddress.contactSex"
	              value="0"
	            />
	            <span>女士</span>
	          </label>
	        </div>
	      </div>
	      
	      <div class="form-group">
	        <label for="contactTel">
	          <i class="fa fa-phone"></i>
	          <span>电话</span>
	        </label>
	        <input
	          type="tel"
	          id="contactTel"
	          v-model="deliveryAddress.contactTel"
	          placeholder="请输入联系电话"
	        />
	      </div>
	      
	      <div class="form-group">
	        <label for="address">
	          <i class="fa fa-map-marker"></i>
	          <span>收货地址</span>
	        </label>
	        <textarea
	          id="address"
	          v-model="deliveryAddress.address"
	          placeholder="请输入详细收货地址"
	          rows="3"
	        ></textarea>
	      </div>
	    </div>
	  </div>

	  <!-- 成功/错误提示 -->
	  <div class="toast-container" v-if="toast.show">
	    <div class="toast" :class="toast.type">
	      <i :class="toast.icon"></i>
	      <span>{{ toast.message }}</span>
	    </div>
	  </div>

	  <div class="button-container">
		<button class="save-btn" @click="updateUserAddress">
		  <i class="fa fa-check"></i> 保存地址
		</button>
	  </div>

	  <!-- 底部菜单部分 -->
	  <Footer></Footer>
	</div>
</template>
  
<script setup>
  import Footer from "../components/Footer.vue";
  import qs from "qs";
  import { useRouter, useRoute } from "vue-router";
  import { ref, onMounted } from "vue";
  import { addressApi } from "../api";
  import { getSessionStorage } from "../common.js";
  
  const router = useRouter();
  const route = useRoute();
  
  const user = getSessionStorage("user");
  const businessId = route.query.businessId;
  const daId = route.query.daId; // 获取地址ID
  const deliveryAddress = ref({
	daId: null,
	contactName: "",
	contactSex: 1,
	contactTel: "",
	address: "",
  });

  // 获取现有地址数据
  const getDeliveryAddressById = async () => {
	if (!daId) {
	  console.warn('没有提供地址ID，无法获取地址详情');
	  return;
	}
	
	try {
	  console.log('正在获取地址详情，ID:', daId);
	  const response = await addressApi.getAddressById(daId);
	  console.log('获取地址详情成功:', response);
	  if (response) {
		deliveryAddress.value = { ...response };
	  } else {
		console.warn('获取到的地址详情为空');
	  }
	} catch (error) {
	  console.error('获取地址详情失败:', error);
	  // 即使获取失败也不弹出提示，允许用户继续编辑
	  // 可能是从地址列表传过来的数据
	  if (route.query && route.query.addressData) {
		try {
		  const addressData = JSON.parse(decodeURIComponent(route.query.addressData));
		  deliveryAddress.value = { ...addressData };
		} catch (e) {
		  console.error('解析传入的地址数据失败:', e);
		}
	  }
	}
  };

  // 页面加载时获取地址数据
  onMounted(() => {
	getDeliveryAddressById();
  });
  
  // 提示消息
  const toast = ref({
	show: false,
	message: '',
	type: 'success',
	icon: 'fa fa-check-circle'
  });

  // 显示提示消息
  const showToast = (message, type = 'success') => {
	toast.value.show = true;
	toast.value.message = message;
	toast.value.type = type;
	toast.value.icon = type === 'success' ? 'fa fa-check-circle' : 'fa fa-exclamation-circle';
	
	// 3秒后自动关闭
	setTimeout(() => {
	  toast.value.show = false;
	}, 3000);
  };

  const updateUserAddress = async () => {
	if (deliveryAddress.value.contactName == "") {
	  showToast("联系人姓名不能为空！", "error");
	  return;
	}
	if (deliveryAddress.value.contactTel == "") {
	  showToast("联系人电话不能为空！", "error");
	  return;
	}
	if (deliveryAddress.value.address == "") {
	  showToast("联系人地址不能为空！", "error");
	  return;
	}
	
	// 不需要手动设置userId，后端会根据当前登录用户获取
	console.log('更新地址数据:', deliveryAddress.value);
	
	try {
	  // 使用API工具更新地址
	  const response = await addressApi.updateAddress(daId, deliveryAddress.value);
	  console.log('更新地址成功:', response);
	  showToast("地址更新成功！");
	  
	  // 延迟跳转，让用户看到成功消息
	  setTimeout(() => {
		router.push({
		  path: "/userAddress",
		  query: { businessId: businessId },
		});
	  }, 1500);
	} catch (error) {
	  console.error('更新地址失败:', error);
	  showToast("地址更新失败！" + (error.message || ""), "error");
	}
  };

  const goBack = () => {
	console.log('返回上一页');
	router.back(); // 使用router.back()代替router.go(-1)更加语义化
  };
  </script>
  
<style scoped>
/*************** 总容器 ***************/
.wrapper {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

/*************** header ***************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  /*保证在最上层*/
  z-index: 1000;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.wrapper header i {
  font-size: 6vw;
  position: absolute;
  left: 4vw;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.wrapper header i:hover {
  transform: translateX(-2px);
}

/*************** 表单容器 ***************/
.form-container {
  padding: 16vw 4vw 6vw;
}

.form-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 4vw;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.form-group {
  margin-bottom: 4vw;
}

.form-group label {
  display: flex;
  align-items: center;
  margin-bottom: 2vw;
  font-size: 3.8vw;
  color: #333;
  font-weight: 500;
}

.form-group label i {
  font-size: 4vw;
  color: #0097ff;
  margin-right: 2vw;
}

.form-group input, .form-group textarea {
  width: 100%;
  padding: 3vw;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  font-size: 3.8vw;
  color: #333;
  background-color: #f9f9f9;
  transition: all 0.3s;
  box-sizing: border-box;
}

.form-group input:focus, .form-group textarea:focus {
  border-color: #0097ff;
  box-shadow: 0 0 0 2px rgba(0, 151, 255, 0.1);
  background-color: #fff;
  outline: none;
}

.form-group textarea {
  resize: none;
  height: auto;
}

/* 性别单选按钮样式 */
.gender-group .radio-group {
  display: flex;
}

.radio-label {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 10vw;
  background-color: #f9f9f9;
  border: 1px solid #e8e8e8;
  margin-right: 3vw;
  border-radius: 8px;
  transition: all 0.3s;
  cursor: pointer;
}

.radio-label:last-child {
  margin-right: 0;
}

.radio-label input {
  position: absolute;
  opacity: 0;
  width: 0;
  height: 0;
}

.radio-label span {
  font-size: 3.8vw;
  color: #666;
}

.radio-label.active {
  background-color: rgba(0, 151, 255, 0.1);
  border-color: #0097ff;
}

.radio-label.active span {
  color: #0097ff;
  font-weight: 500;
}

/*************** 按钮样式 ***************/
.button-container {
  padding: 0 4vw;
  margin-bottom: 14vw;
}

.save-btn {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;
  color: white;
  font-size: 4.2vw;
  font-weight: 500;
  border: none;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 4px 12px rgba(0, 151, 255, 0.3);
  transition: transform 0.2s, box-shadow 0.2s;
  cursor: pointer;
}

.save-btn:active {
  transform: scale(0.98);
  box-shadow: 0 2px 8px rgba(0, 151, 255, 0.2);
}

.save-btn i {
  font-size: 4.2vw;
  margin-right: 2vw;
}

/* 提示消息样式 */
.toast-container {
  position: fixed;
  top: 20%;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  z-index: 2000;
  pointer-events: none;
}

.toast {
  padding: 3vw 6vw;
  border-radius: 8px;
  display: flex;
  align-items: center;
  font-size: 3.8vw;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  animation: fadeInOut 0.3s ease;
}

.toast.success {
  background-color: rgba(56, 202, 115, 0.95);
  color: white;
}

.toast.error {
  background-color: rgba(255, 77, 79, 0.95);
  color: white;
}

.toast i {
  font-size: 4.5vw;
  margin-right: 3vw;
}

@keyframes fadeInOut {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>